package book.security;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;

public class SignatureTest {

	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
		
		KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
		gen.initialize(512);
		KeyPair keyPair = gen.generateKeyPair();
		Signature signature = Signature.getInstance(gen.getAlgorithm());
		
		//用密钥生成签名
		signature.initSign(keyPair.getPrivate());
		byte[] data = "Data Signature".getBytes();
		signature.update(data);
		byte[] sign = signature.sign();
		
		//验证公钥的签名是否正确
		signature.initVerify(keyPair.getPublic());
		signature.update(data);
		System.out.println(signature.verify(sign));
	}
}
